<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区 -->
    <el-card class="box-card">
      <el-alert title="添加商品信息" type="info" center show-icon :closable="false"> </el-alert>
      <!-- 步骤条区域 -->
      <el-steps :space="400" :active="activeIndex - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" label-position="top">
        <!-- tab 栏切换区 -->
        <el-tabs v-model="activeIndex" :tab-position="'left'" :before-leave="beforeTabLeave">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goodName"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" props="goods_cat">
              <el-select v-model="good_cateId" placeholder="请选择">
                <el-option v-for="item in cateList" :key="item.id" :label="item.cateName" :value="item.id"> </el-option>
              </el-select>
            </el-form-item>
          </el-tab-pane>

          <el-tab-pane label="商品图片" name="1">
            <!-- action 表示图片要上传到的后台 API 地址 -->
            <el-upload name="goodsImg" :action="uploadURL" :auto-upload="autoUpload" :before-upload="beforeAvatarUpload" :on-preview="handlePreview" list-type="picture" :on-success="handleSuccess">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>

          <el-tab-pane label="商品内容" name="2">
            <quill-editor v-model="addForm.introduce"></quill-editor>
            <el-button type="primary" class="btnAdd" @click="add">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 图片预览对话框 -->
    <el-dialog title="图片预览" :visible.sync="previewVisible" width="50%">
      <img :src="previewPath" alt="" class="previewImg" />
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    const checkPrice = (rule, value, cb) => {
      const regPrice = /^[0-9]{1,}\.[0-9]{2}/
      return regPrice.test(value) ? cb() : cb(new Error('请输入合法的价格, xx.00'))
    }

    return {
      activeIndex: '0',
      // 添加商品的表单数据对象
      addForm: {
        goodName: '',
        price: 0,
        weight: 0,
        number: 0,
        introduce: '',
        pictureName: ''
      },
      // 商品分类 id
      good_cateId: '',
      // 添加商品表单的验证规则
      addFormRules: {
        goodName: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' },
          { validator: checkPrice, trigger: 'blur' }
        ],
        weight: [{ required: true, message: '请输入商品重量', trigger: 'blur' }],
        number: [{ required: true, message: '请输入商品数量', trigger: 'blur' }]
      },
      // 商品分类列表
      cateList: [],
      // 上传图片的 url 地址
      uploadURL: 'http://127.0.0.1:82/goods/upload.do',
      autoUpload: true,
      previewPath: '',
      previewVisible: false
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    // 获取商品分类列表
    async getCateList() {
      const { data: res } = await this.$axios.get('/category/findAll.do')
      if (!res.flag) return this.$message.error(res.message)
      this.cateList = res.data
    },
    // 标签切换前的验证
    beforeTabLeave(activeName, oldActiveName) {
      // oldActiveName 即将离开的页面
      // activeName 即将进入的页面
      if (this.good_cateId === '' && oldActiveName === '0') {
        this.$message.error('请先选择商品分类')
        return false
      }
    },
    // 处理图片预览效果
    handlePreview(file) {
      this.previewPath = this.addForm.pictureName
      this.previewVisible = true
    },
    // 上传图片之前执行
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.warning('上传套餐图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.warning('上传套餐图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 监听图片上传成功的事件
    handleSuccess(response) {
      if (!response.flag) return this.$message.error(response.data.message)
      this.$message.success(response.message)
      this.addForm.pictureName = 'http://qxz1cipq3.hn-bkt.clouddn.com/' + response.data
    },
    // 添加商品
    add() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return false

        const { data: res } = await this.$axios.post(`/goods/add.do?id=${this.good_cateId}`, this.addForm)
        if (!res.flag) return this.$message.error(res.message)
        this.$message.success(res.message)

        this.$router.push('/goods')
      })
    }
  }
}
</script>

<style lang="less" scoped>
.previewImg {
  width: 100%;
}

.btnAdd {
  margin-top: 15px;
}
</style>
